package com.jd.webapp.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jd.goods.pojo.GoodsCategory;
import com.jd.goods.service.GoodsCategoryService;
import com.jd.webapp.pojo.EasyUITreeNode;

/*
 * 耦合性强，与前端使用的框架直接关联，受前端代码的影响很大，
 * 也就是说，前端改变会导致后台代码的修改
 */
@Controller
public class GoodsCatController {
	@Autowired
	private GoodsCategoryService goodsCategoryService;
	
	@RequestMapping("/item/cat/list")
	public @ResponseBody Object getItemCatList(@RequestParam(defaultValue="0") Long id){
		List<EasyUITreeNode> nodes = new ArrayList<EasyUITreeNode>();
		try {
			List<GoodsCategory> list = goodsCategoryService.getGoodsCatsByParentId(id);
			for(GoodsCategory cat : list){
				EasyUITreeNode node = itemCatToEasyUITreeNode(cat);
				nodes.add(node);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nodes;
	}
	
	//将商品分类转化成easyui tree 需要的数据格式：EasyUITreeNode
	private EasyUITreeNode itemCatToEasyUITreeNode(GoodsCategory itemcat){
		EasyUITreeNode node = new EasyUITreeNode();
		node.setId(itemcat.getId());
		node.setText(itemcat.getName());
		node.setState(itemcat.getIsParent()?"closed":"open");
		return node;
	}
}
